import axios, { AxiosInstance, InternalAxiosRequestConfig, AxiosResponse, AxiosError } from 'axios'
import { Toast } from 'vant'
import Vue from 'vue'

Vue.use(Toast)

const request: AxiosInstance = axios.create({
  baseURL: 'http://smart-shop.itheima.net/index.php?s=/api'
})
request.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    Toast.loading({
      message: '请求中...',
      forbidClick: true,
      loadingType: 'spinner',
      duration: 0
    })
    return config
  },
  (error: AxiosError) => {
    return Promise.reject(error)
  }
)

interface ResponseData<T= unknown> {
  code: number;
  message: string;
  status: number;
  data: T;
}
request.interceptors.response.use(
  (response: AxiosResponse<ResponseData>) => {
    const res = response.data
    if (res.status !== 200) {
      Toast(res.message)
      return Promise.reject(res.message)
    } else {
    // 清除 loading 中的效果
      Toast.clear()
    }
    return response
  },
  (error: AxiosError) => {
    return Promise.reject(error)
  }
)
export default request
